<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  id: logUser.id,
  info: '',
  // ----
  forAdm: String(proxy.$Phone) === String(logUser.telphone)
})
// ----
const moveTime = 50
let showMarquee = null
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const sliding = ref()
const layer = ref()

/* ---- */
const setMarquee = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    const forLi = el.innerHTML
    if (Number(el.firstChild.offsetWidth) > Number(el.offsetWidth)) {
      el.innerHTML = forLi + forLi
      showMarquee = setInterval(marqueefun, moveTime)
    }
  }
}
const marqueefun = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    if (Number(el.lastChild.offsetWidth) <= Number(el.scrollLeft)) {
      el.scrollLeft = el.scrollLeft - el.firstChild.offsetWidth
    } else {
      el.scrollLeft = el.scrollLeft + 1
    }
  }
}
const stopRolling = () => {
  if (showMarquee) {
    clearInterval(showMarquee)
    showMarquee = null
  } else {
    showMarquee = setInterval(marqueefun, moveTime)
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取指定系统管理员id--
  if (!user.forAdm) {
    await proxy.$http.get('dealer/index', {
      params: { 'DealerSearch[telphone]': proxy.$Phone }
    }).then((res) => {
      if (Number(res.items.length) > 0) user.id = res.items[0].id
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // --获取合作商家文字广告--
  const promoteData = forSys.filter((item) => { return String(item.name) === 'market_promote' })
  if (Number(promoteData.length) === 1) {
    const PEData = promoteData[0]
    await proxy.$Myfun.getJsonData(PEData.value, (resJson) => {
      const curRes = resJson[0] || {}
      // ----
      if (curRes.remark && Number(curRes.remark.length) > 0) user.info = proxy.$Myfun.setText(curRes.remark)
    })
  }
  // ----
  if (user.info) nextTick(() => { setMarquee() })
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 15 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'common-type/index',
    forData: {
      params: {
        'CommonTypeSearch[dealer_id]': user.id,
        // --合作商家分类--
        'CommonTypeSearch[type]': 1,
        // ----
        sort: 'SORT_ASC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getNeedDate = async (curItem) => {
  await proxy.$http.get('program/index', {
    params: {
      'ProgramSearch[common_type_id]': curItem.id,
      'ProgramSearch[dealer_id]': curItem.dealer_id
    }
  }).then((res) => {
    curItem.count = res._meta.totalCount
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const curItem = {
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      // ----
      dealer_id: item.dealer_id,
      // ----
      count: 0
    }
    // ----
    await getNeedDate(curItem)
    // ----
    newItems.push(curItem)
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'PromoteSysList', { id: item.id })
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray" v-if="user.info">
      <div class="forTop xw-bgCL-11 xw-flex xw-flex-align">
        <div class="TOP-msg xw-Lfg xw-flex-W1">
          <div class="forMarquee">
            <div ref="forMarquee" class="FMQ-con xw-act xw-flex xw-flex-align" @click="stopRolling">
              <ul class="xw-flex-W1">
                <li>{{user.info}}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-class xw-flex xw-flex-column" ref="dataList">
          <li class="xw-Tfg xw-bg-white xw-act-bg xw-flex xw-flex-align" v-for="(item, index) in items">
            <div class="LCS-title xw-ellipsis xw-flex-W1 xw-flex xw-flex-align" @click="getAuditFun(1, item)">
              <div class="xw-ellipsis">{{item.name}}</div>
              <span>（{{item.count}}）</span>
            </div>
            <i class="fal fa-angle-right"></i>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.TOP-msg { padding: 0 0 0 0.4rem; }
.TOP-msg:before { top: 0.2rem; bottom: 0.2rem; width: 0.8rem; background: #ffffff; }

/* ---- */
.forMarquee { height: 100%; padding: 0 1rem; }
.FMQ-con { height: 100%; }
.FMQ-con ul { white-space: nowrap; overflow: hidden; }
.FMQ-con li { display: inline-block; font-size: 1.7rem; font-weight: bold; }


/* ---- */
.list-class li { padding: 0 1rem; }
.list-class li:before { left: 1rem; }
.list-class li:nth-of-type(1):before { display: none; }
.list-class li i { margin-left: 1rem; font-size: 2rem; color: #bbbbbb; }
.LCS-title { padding: 1.3rem 0; font-size: 1.7rem; }
.LCS-title div { max-width: 100%; }
.LCS-btn { margin: 0 0 0 1.2rem; padding: 1.4rem 0; }
.LCS-btn em { margin-right: 0.5rem; color: #aaaaaa; }
</style>